'''
Created on Feb 14, 2011

@author: arfuller
'''

from google.appengine.api import channel
from google.appengine.ext import deferred
from google.appengine.api import prospective_search

def send(event, handler=None):
  dict = event._populate_entity()
  try:
    channel.send_message(event.player_id, '%s|%s|%s' % (event.event, dict['reference'], event.detail or ''))
  except channel.InvalidChannelClientIdError:
    pass
  prospective_search.match(event)
  if handler:
    handler(event)
    #deferred.defer(handler, event)

def register_query(event_class, query, client_id):
  prospective_search.subscribe(event_class, query, client_id)

def handle_query_matches(client_ids, event):
  for client_id in client_ids:
    try:
      channel.send_message(client_id, str(event))
    except channel.InvalidChannelClientIdError:
      prospective_search.unsubscribe(event.__class__, client_id)


